import { Component, OnDestroy, OnInit } from '@angular/core';

import { NavController, Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { Storage } from '@ionic/storage';
import { TranslateService } from '@ngx-translate/core';
import { BackService } from './service/back.service';

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit, OnDestroy {

    constructor(
        private platform: Platform,
        private splashScreen: SplashScreen,
        private statusBar: StatusBar,
        private storage: Storage,
        private translate: TranslateService,
        private navCtrl: NavController,
        private backSrv: BackService
    ) { }

    async ngOnInit() {
        await this.initializeApp();
    }

    ngOnDestroy() {

    }

    ionViewDidLoad() {

    }

    async initializeApp() {
        this.platform.ready().then(async () => {
            this.statusBar.styleDefault();
            this.statusBar.backgroundColorByHexString('#009e41');
            this.splashScreen.hide();

            await this.initI18nSettings();
            this.backSrv.registerBackButtonListener(['/guest-home', '/patient-app/patient-home', '/doctor-app/doctor-home']);

            const userId = localStorage.getItem('userId');
            const userType = localStorage.getItem('userType');
            const authToken = localStorage.getItem('auth-token');
            const intUserType = Number(userType);

            if (userId && userType && authToken) {
                if (intUserType === 1) {
                    await this.navCtrl.navigateRoot('/patient-app');
                } else if (intUserType === 2 || intUserType === 3) {
                    await this.navCtrl.navigateRoot('/doctor-app');
                }
            }
        });
    }

    async initI18nSettings() {
        let currentLanguage = this.translate.getBrowserCultureLang();
        const [ languageFirst, languageSecond ] = currentLanguage.split('-');
        currentLanguage = `${languageFirst.toLowerCase()}-${languageSecond.toUpperCase()}`;
        this.translate.setDefaultLang(currentLanguage);
        this.translate.use(currentLanguage);

        // const currentLanguage = await localStorage.getItem('currentLanguage') || this.translate.getBrowserCultureLang();
        // this.translate.setDefaultLang('zh-CN');
        // this.translate.use(currentLanguage);
        // localStorage.setItem('currentLanguage', currentLanguage);
    }
}
